<template>
  <div class="visit-date-picker">
    <div class="register-date-box" @click="toggle">
      <slot name="display" :date="modelValue" :displayText="displayText">
        {{ displayText }}
      </slot>
    </div>
    <div v-if="open" class="register-date-custom-picker" @click.stop>
      <DatePickerTime
        :time="modelValue"
        @change="onInnerChange"
        @update:modelValue="onInnerChange"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue';
import dayjs from 'dayjs';
import DatePickerTime from '@/components/DatePickerTime/index.vue';

interface Props {
  modelValue: string | Date;
  displayFormat?: string; // 展示格式
}

const props = withDefaults(defineProps<Props>(), {
  displayFormat: 'MM-DD'
});

const emit = defineEmits<{
  (e: 'update:modelValue', v: string | Date): void;
  (e: 'change', v: string | Date): void;
}>();

const open = ref(false);
const toggle = () => (open.value = !open.value);

const displayText = computed(() => {
  if (!props.modelValue) return '';
  return dayjs(props.modelValue).format(props.displayFormat);
});

function onInnerChange(v: string | Date) {
  emit('update:modelValue', v);
  emit('change', v);
  open.value = false; // 选完关闭
}

// 点击外部关闭
function onDocClick(e: MouseEvent) {
  if (!(e.target as HTMLElement).closest('.visit-date-picker')) {
    open.value = false;
  }
}

watch(open, (val) => {
  if (val) document.addEventListener('mousedown', onDocClick);
  else document.removeEventListener('mousedown', onDocClick);
});

</script>

<style scoped lang="scss">
.visit-date-picker {
  position: relative;
  display: inline-block;
}
.register-date-box {
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 4px 8px;
  border: 1px solid transparent;
  min-width: 54px;
  height: 32px;
  border-radius: 4px;
  font-size: 14px;
  color: #333;
  background: #fff;
  transition: all .15s;
  &:hover {
    background: #f5f7fa;
  }
}

</style>
